package com.example.choupaiapp.main.activity.find;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.common.util.DialogUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.common.view.TabEntity;
import com.example.choupaiapp.common.view.statusbar.StatusView;
import com.example.choupaiapp.main.activity.home.SearchResultActivity;
import com.example.choupaiapp.main.activity.message.ChatActivity;
import com.example.choupaiapp.main.activity.mine.FollowFasActivity;
import com.example.choupaiapp.main.bean.MsgUser;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.constant.Config;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.fragment.find.FindAllFragment;
import com.example.choupaiapp.main.fragment.find.FindTextImageFragment;
import com.example.choupaiapp.main.fragment.find.FindVideoFragment;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.hyphenate.easeui.EaseConstant;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.tencent.tauth.Tencent;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by ASUS on 2020/5/20.
 */

public class FindOtherInfoActivity extends CommonActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.head_photo)
    CircleImageView headPhoto;
    @BindView(R.id.vip_img)
    ImageView vipImg;
    @BindView(R.id.username)
    TextView username;
    @BindView(R.id.description)
    TextView description;
    @BindView(R.id.follow)
    TextView follow;
    @BindView(R.id.follow_num)
    TextView followNum;
    @BindView(R.id.fans_num)
    TextView fansNum;
    @BindView(R.id.linear)
    LinearLayout linear;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.username_top)
    TextView usernameTop;
    @BindView(R.id.title_ll)
    LinearLayout titleLl;
    @BindView(R.id.title_rl)
    RelativeLayout title_rl;
    @BindView(R.id.status_view_top)
    StatusView status_view_top;
    @BindView(R.id.tablayout)
    CommonTabLayout tabLayout;
    private String userId;
    @BindView(R.id.mine_bg_img)
    ImageView mine_bg_img;
    private Tencent mTencent;
    @BindView(R.id.private_msg)
    TextView private_msg;
    @BindView(R.id.appbar)
    AppBarLayout appbar;

    private String[] mTitles = new String[3];
    private ArrayList<Fragment> mFragments = new ArrayList<>();//存放Fragment
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private MyPagerAdapter myPagerAdapter;
    private UserInfoBean mUserInfoBean;
    private UserInfoBean userInfoBean;
    private String categoriesId;
    private int position;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other_info);
    }

    @SuppressLint("RestrictedApi")
    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            userId = bundle.getString("userId");
            categoriesId = bundle.getString("categoriesId");
            position = bundle.getInt("position");
        }

        userInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");

        if (userInfoBean == null) {
            finishActivity();
        }

        EventBus.getDefault().register(this);

        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));

        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
                if (Math.abs(i) <= 0) {
                    usernameTop.setTextColor(getResources().getColor(R.color.transparent));
                    title_rl.setBackgroundColor(getResources().getColor(R.color.transparent));
                    status_view_top.setBackgroundColor(getResources().getColor(R.color.transparent));
                } else if (Math.abs(i) > 0 && Math.abs(i) <= linear.getHeight() / 2) {
                    float f = (float) Math.abs(i) / (float) linear.getHeight();
                    float alpha = (float) 255 * f * 2;
                    usernameTop.setTextColor(Color.argb((int) alpha, 0, 0, 0));
                    title_rl.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
                    status_view_top.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
//                status_view_top.setBackgroundColor(Color.argb((int) alpha, 204, 204, 204));
                } else {
                    usernameTop.setTextColor(getResources().getColor(R.color.color_333));
                    title_rl.setBackgroundColor(getResources().getColor(R.color.white));
                    status_view_top.setBackgroundColor(getResources().getColor(R.color.white));
//                status_view_top.setBackgroundColor(getResources().getColor(R.color.normal_status));
                }
            }
        });


        mTitles[0] = "全部";
        mTitles[1] = "图文";
        mTitles[2] = "视频";

        tabLayout.setTextSelectColor(getResources().getColor(R.color.color_333));
        tabLayout.setTextUnselectColor(getResources().getColor(R.color.color_8888));
        tabLayout.setIndicatorColor(getResources().getColor(R.color.color_333));
        tabLayout.setIndicatorHeight(2f);
        tabLayout.setIndicatorCornerRadius(1f);
        tabLayout.setIndicatorWidth(40f);
        tabLayout.setTextsize(15);


        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i]));
        }

        myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
        viewpager.setAdapter(myPagerAdapter);
        tabLayout.setTabData(mTabEntities);

        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewpager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {
            }
        });


        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabLayout.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }


        });

        viewpager.setCurrentItem(0);
        viewpager.setOffscreenPageLimit(3);


    }

    @Override
    protected void initData() {
        showDialog(this, null);
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.WATCH_OTHER_INFO + userId, null, Url.WATCH_OTHER_INFO, new Callback<UserInfoBean>() {
            @Override
            public void onSuccess(UserInfoBean userInfoBean) {
                dismissDialog();
                if (userInfoBean.getCode() == Contacts.SUCCESS) {
                    mUserInfoBean = userInfoBean;
                    refreshLayout.finishRefresh();

                    if (FindOtherInfoActivity.this.userInfoBean.getUser().getUserId() == mUserInfoBean.getUser().getUserId()) {
                        follow.setVisibility(View.INVISIBLE);
                        private_msg.setVisibility(View.INVISIBLE);
                    } else {
                        follow.setVisibility(View.VISIBLE);
                        private_msg.setVisibility(View.VISIBLE);
                    }

                    username.setText(userInfoBean.getUser().getNickname());
                    if (userInfoBean.getUser().getNickname().length() > 7) {
                        usernameTop.setText(userInfoBean.getUser().getNickname().substring(0, 7) + "...");
                    } else {
                        usernameTop.setText(userInfoBean.getUser().getNickname());
                    }
                    description.setText(userInfoBean.getUser().getSignature());
                    followNum.setText(userInfoBean.getUser().getAttentionSum() + "");
                    fansNum.setText(userInfoBean.getUser().getFansSum() + "");

                    Glide.with(context)
                            .load(userInfoBean.getUser().getAvatar() + Config.IMAGE_LIM)
                            .dontAnimate()
                            .placeholder(R.mipmap.icon_no_head)
                            .centerCrop()
                            .into(headPhoto);

                    Glide.with(context)
                            .load(userInfoBean.getUser().getBackgroundImg() + Config.IMAGE_LIM)
                            .dontAnimate()
                            .centerCrop()
                            .into(mine_bg_img);

                    if (userInfoBean.getUser().getIsAttention() == 0) {
                        follow.setText("关注");
                        follow.setBackgroundResource(R.drawable.shape_yellow_oval);
                    } else {
                        follow.setText("已关注");
                        follow.setBackgroundResource(R.drawable.shape_gray_oval);
                    }

                    EventBus.getDefault().post("refresh_find_tab_data");

                    if (mFragments.size() < 3) {
                        viewpager.post(new Runnable() {
                            @Override
                            public void run() {
                                // 填充 Viewpager 的界面
                                String isSelf = "0";
                                if (userInfoBean.getUser().getUserId() == FindOtherInfoActivity.this.userInfoBean.getUser().getUserId()) {
                                    isSelf = "1";
                                } else {
                                    isSelf = "0";
                                }
                                FindAllFragment mineAllFragment = FindAllFragment.newInstance(userInfoBean, isSelf, mUserInfoBean.getUser().getContentHidden());
                                mFragments.add(mineAllFragment);

                                FindTextImageFragment mineImgTextFragment = FindTextImageFragment.newInstance(userInfoBean, isSelf, mUserInfoBean.getUser().getContentHidden());
                                mFragments.add(mineImgTextFragment);

                                FindVideoFragment mineVideoFragment = FindVideoFragment.newInstance(userId, isSelf, mUserInfoBean.getUser().getContentHidden());
                                mFragments.add(mineVideoFragment);

                                myPagerAdapter.notifyDataSetChanged();
                            }
                        });
                    }

                } else {
                    refreshLayout.finishRefresh();
                    if (userInfoBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(userInfoBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                dismissDialog();
                refreshLayout.finishRefresh();
            }
        });


    }


    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
        }
    }

    //    @Override
    @OnClick({R.id.follow, R.id.private_msg, R.id.search, R.id.more, R.id.follow_num, R.id.follow_tv, R.id.fans_num, R.id.fans_tv})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.follow:
                if (mUserInfoBean != null) {
                    if (mUserInfoBean.getUser().getIsAttention() == 0) {
                        showDialog(context, "关注中...");
                        finalOkGo.requestHead(RequestType.GETHEAD, Url.FOLLOW_OTHER + mUserInfoBean.getUser().getUserId(), null, Url.FOLLOW_OTHER, new Callback<SendCodeBean>() {
                            @Override
                            public void onSuccess(SendCodeBean sendCodeBean) {
                                dismissDialog();
                                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                    mUserInfoBean.getUser().setIsAttention(1);
                                    follow.setText("已关注");
                                    follow.setBackgroundResource(R.drawable.shape_gray_oval);
//                                    EventBus.getDefault().post("refresh_home_follow");
                                    if (!TextUtils.isEmpty(categoriesId)) {
                                        EventBus.getDefault().post("refresh_detail_follow:" + categoriesId + ":" + mUserInfoBean.getUser().getUserId());
                                    }
                                    EventBus.getDefault().post("refresh_find_detail_follow");
                                    EventBus.getDefault().post("refresh_detail_other_follow");
                                    EventBus.getDefault().post("refresh_mine");
                                } else {
                                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                    } else {
                                        showImageToas(sendCodeBean.getMsg());
                                    }
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                dismissDialog();
                            }
                        });
                    } else {
                        showDialog(context, "取消关注...");
                        finalOkGo.requestHead(RequestType.GETHEAD, Url.CANCEL_FOLLOW + mUserInfoBean.getUser().getUserId(), null, Url.CANCEL_FOLLOW, new Callback<SendCodeBean>() {
                            @Override
                            public void onSuccess(SendCodeBean sendCodeBean) {
                                dismissDialog();
                                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                    mUserInfoBean.getUser().setIsAttention(0);
                                    follow.setText("关注");
                                    follow.setBackgroundResource(R.drawable.shape_yellow_oval);
//                                    EventBus.getDefault().post("refresh_home_follow");
                                    if (!TextUtils.isEmpty(categoriesId)) {
                                        EventBus.getDefault().post("refresh_detail_cancel_follow:" + categoriesId + ":" + mUserInfoBean.getUser().getUserId());
                                    }
                                    EventBus.getDefault().post("refresh_find_detail_cancel_follow");
                                    EventBus.getDefault().post("refresh_detail_other_cancel_follow");
                                    EventBus.getDefault().post("refresh_mine");
                                } else {
                                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                    } else {
                                        showImageToas(sendCodeBean.getMsg());
                                    }
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                dismissDialog();
                            }
                        });
                    }
                }
                break;
            case R.id.private_msg:
                MsgUser msgUser = new MsgUser();
                msgUser.setUserName(mUserInfoBean.getUser().getNickname());
                msgUser.setUserHead(mUserInfoBean.getUser().getAvatar());
                SharedPreferencesHelp.putBean("HX_" + mUserInfoBean.getUser().getUserId(), msgUser);

                Intent intent = new Intent(this, ChatActivity.class);
                intent.putExtra(EaseConstant.EXTRA_USER_ID, "HX_" + mUserInfoBean.getUser().getUserId());
                startActivity(intent);
                MobclickAgent.onEvent(ContextUtil.getContext(), "directMessageID");
                break;
            case R.id.more:
                if (userInfoBean == null || userInfoBean.getUser().getUserId() == mUserInfoBean.getUser().getUserId()) {
                    return;
                }
                DialogUtil.getInstance().showCenterDialog(context, R.layout.dialog_more);
                LinearLayout dialog_more = (LinearLayout) DialogUtil.getInstance().dialog_center_layout;
                dialog_more.findViewById(R.id.report).setVisibility(View.GONE);

                LinearLayout black_list = dialog_more.findViewById(R.id.black_list);
                LinearLayout delete = dialog_more.findViewById(R.id.delete);

                LinearLayout cancel_follow = dialog_more.findViewById(R.id.cancel_follow);
                View line = dialog_more.findViewById(R.id.line);
                View viewd = dialog_more.findViewById(R.id.view);
                View view1 = dialog_more.findViewById(R.id.view1);
                view1.setVisibility(View.GONE);
                line.setVisibility(View.GONE);
                viewd.setVisibility(View.INVISIBLE);
                delete.setVisibility(View.GONE);

                cancel_follow.setVisibility(View.GONE);

                if (userInfoBean.getUser().getUserId() == mUserInfoBean.getUser().getUserId()) {
                    black_list.setVisibility(View.GONE);
                } else {
                    black_list.setVisibility(View.VISIBLE);
                }

                black_list.setOnClickListener(view110 -> {
                    if (Utils.isDoubleClick()) {
                        return;
                    }
                    DialogUtil.getInstance().dialog_center.dismiss();
                    showDialog(context, "屏蔽中...");
                    finalOkGo.requestHead(RequestType.POSTHEAD, Url.ADD_BLACK_LIST + mUserInfoBean.getUser().getUserId(), null, Url.ADD_BLACK_LIST, new Callback<SendCodeBean>() {
                        @Override
                        public void onSuccess(SendCodeBean sendCodeBean) {
                            dismissDialog();
                            if (sendCodeBean.getCode() == Contacts.SUCCESS) {
//                                EventBus.getDefault().post("refresh_home_follow");
                                if (!TextUtils.isEmpty(categoriesId)) {
                                    EventBus.getDefault().post("black_detail_list:" + categoriesId + ":" + mUserInfoBean.getUser().getUserId());
                                }
                                finishActivity();
                            } else {
                                if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                } else {
                                    showImageToas(sendCodeBean.getMsg());
                                }
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            dismissDialog();
                        }
                    });

                });
                break;
            case R.id.search:
                Bundle bundle4 = new Bundle();
                bundle4.putString("name", mUserInfoBean.getUser().getNickname());
                startFinishActivity(SearchResultActivity.class, bundle4);
                break;
            case R.id.follow_num:
                Bundle bundle = new Bundle();
                bundle.putString("flag", "other_follow");
                bundle.putString("userid", userId);
                startActivity(FollowFasActivity.class, bundle);
                break;
            case R.id.fans_num:
                Bundle bundle1 = new Bundle();
                bundle1.putString("flag", "other_fans");
                bundle1.putString("userid", userId);
                startActivity(FollowFasActivity.class, bundle1);
                break;
            case R.id.follow_tv:
                Bundle bundle2 = new Bundle();
                bundle2.putString("flag", "other_follow");
                bundle2.putString("userid", userId);
                startActivity(FollowFasActivity.class, bundle2);
                break;
            case R.id.fans_tv:
                Bundle bundle3 = new Bundle();
                bundle3.putString("flag", "other_fans");
                bundle3.putString("userid", userId);
                startActivity(FollowFasActivity.class, bundle3);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        String s = event.split(":")[0];
        if (s.equals("refresh_detail_other_follow")) {
            mUserInfoBean.getUser().setIsAttention(1);
            follow.setText("已关注");
            follow.setBackgroundResource(R.drawable.shape_gray_oval);
            if (!TextUtils.isEmpty(categoriesId)) {
                EventBus.getDefault().post("refresh_detail_follow:" + categoriesId + ":" + mUserInfoBean.getUser().getUserId());
            }
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        initData();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
